package frame.service.standard.impl;

import frame.service.context.ServiceContext;
import frame.service.standard.Constants;
import frame.service.standard.MiayFilter;
import frame.service.standard.MiayRuntimeException;
import frame.service.util.FrameUtil;
import http.RedisSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import util.SecurityUtil;
import util.SessionManager;

import java.util.Map;

public class SecureRequestFilter implements MiayFilter {
    Logger logger = LoggerFactory.getLogger(SecureRequestFilter.class);

    @Override
    public void doPass(ServiceContext serviceContext) {
        String session_key = serviceContext.getReqContentString(Constants.SECRET_REQUEST_SESSION_KEY);
        String timeStamp = serviceContext.getReqContentString(Constants.SECRET_REQUEST_TIMESTAMP);
        String data = serviceContext.getReqContentString(Constants.SECRET_REQUEST_DATA);
        String mac = serviceContext.getReqContentString(Constants.SECRET_REQUEST_MAC);

        RedisSession redisSession = SessionManager.getSession(session_key);
        if(redisSession==null){
            logger.error("Invalid session");
            throw new MiayRuntimeException("930003");
        }

        String sessionSecret = redisSession.getSessionSecret();
        String requestData = SecurityUtil.aesCbcP7Decrypt(sessionSecret, sessionSecret, SecurityUtil.base64Decode(data));
        String reqMac = SecurityUtil.sha256((redisSession.getSessionKey()+requestData+timeStamp).getBytes());
        if(!reqMac.equals(mac)){
            logger.error("Unsecure network environment");
            throw new MiayRuntimeException("930002");
        }else{
            MDC.put(Constants.LOG_SESSION_UUID, session_key);
            //会话加密验证完成后，获取会话信息至context
            serviceContext.setRedisSession(redisSession);
            serviceContext.setReqData(FrameUtil.str2Obj(requestData, Map.class));
            logger.info(requestData);
        }
    }

    /**
     * SAFE_MODE_SECURE 模式下进行交易检查
     * */
    @Override
    public boolean checkSuit(ServiceContext context) {
        String safeMode = context.getReqContentString(Constants.REQUEST_SAFE_MODE);
        return Constants.SAFE_MODE_SECURE.equals(safeMode);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
